#! /usr/bin/env python
# -*- coding: utf-8 -*-
import web
import json
import config

from application.utilities.ctGet import ZF
from application.utilities.ctAnalytics import ctAnalytics

#存储客户端信息
clients = {}

#用于返回统一格式内容
def json_response(error,result,message=""):
    web.header('Content-Type', 'application/json')
    response = {'error':error,'result':result,'message': message}
    return json.dumps(response)

class index:
        def GET(self):
                return "welcome to campus_zf api!"

class pre:
        def GET(self):
                request = web.input()
                if not request.has_key('campus_id'):
                    return json_response(True,"paramError","campus_id不能为空！")

                if not config.campus_setting.has_key(request['campus_id']):
                     return json_response(True,"paramError","campus_id不支持！")

                setting = config.campus_setting[request['campus_id']]

                zfClass  = ZF(setting)
                response = zfClass.pre()

                if response['error']:
                    return json_response(True,response['result'],response['message'])

                clients[response['result']['token']] = zfClass

                #返回
                return json_response(False,response['result'],response['message'])

class login:
        def POST(self):
                #获取并验证传入参数
                request = web.input()
                if not request.has_key('username') or request['username'] == "":
                    return json_response(True,"paramError","学号不能为空！")
                if not request.has_key('password') or request['password'] == "":
                    return json_response(True,"paramError","密码不能为空！")
                if not request.has_key('token') or request['token'] == "":
                    return json_response(True,"paramError","token不能为空！")

                zfClass = clients.get(request['token'], 0)
                if zfClass == 0:
                    return json_response(True,"tokenTimeOut","token过期！")

                response = zfClass.login(request)

                if response['error']:
                    return json_response(True,response['result'],response['message'])

                #返回
                return json_response(False,response['result'],response['message'])

class verify:
        def POST(self):
                #获取并验证传入参数
                request = web.input()
                if not request.has_key('token') or request['token'] == "":
                    return json_response(True,"paramError","token不能为空！")

                zfClass = clients.get(request['token'], 0)
                if zfClass == 0:
                    return json_response(True,"tokenTimeOut","token过期！")

                #获取
                response = zfClass.get_main() 

                if response['error']:
                    return json_response(True,response['result'],response['message'])

                #返回
                return json_response(False,True,response['message'])

class info:
        def POST(self):
                #获取并验证传入参数
                request = web.input()
                if not request.has_key('token') or request['token'] == "":
                    return json_response(True,"paramError","token不能为空！")

                zfClass = clients.get(request['token'], 0)
                if zfClass == 0:
                    return json_response(True,"tokenTimeOut","token过期！")

                #获取
                response = zfClass.get_info() 

                if response['error']:
                    return json_response(True,response['result'],response['message'])

                #分析
                try:
                    response['result'] = ctAnalytics().info_do(response['result'])
                except KeyError:
                    return json_response(True,"","页面分析出错！")

                #获取
                responsePhoto = zfClass.get_photo()

                if responsePhoto['error']:
                    return json_response(True,responsePhoto['result'],responsePhoto['message'])

                response['result']['title'].append("照片")
                response['result']['data'].append(responsePhoto["result"])

                #统一数据格式
                rowData = response['result']['data']
                result    = {}
                result['title']=[
                    "学号",
                    "姓名",
                    "性别",
                    "学院",
                    "专业",
                    "班级",
                    "导师",
                    "生日",
                    "身份证号",
                    "民族",
                    "政治面貌",
                    "毕业院校",
                    "家庭住址",
                    "照片"
                ]
                result['data']={
                    'xh'  : rowData[0], #学号
                    'xm'  : rowData[3], #姓名
                    'xb'  : rowData[9], #性别
                    'xy'  : rowData[36], #学院
                    'zy'  : rowData[42], #专业
                    'bj'  : rowData[47], #班级
                    'ds'  : '', #导师
                    'sr'  : rowData[12], #生日
                    'sfzh': rowData[31], #身份证号
                    'mz'  : rowData[15], #民族
                    'zzmm': rowData[21], #政治面貌
                    'byyx': rowData[13], #毕业院校
                    'jtzz': rowData[41], #家庭住址
                    'zp'  : rowData[61], #照片
                }
                result['row'] = {}
                
                #返回
                return json_response(False,result,response['message'])

class table:
        def POST(self):
                #获取并验证传入参数
                request = web.input()
                if not request.has_key('token') or request['token'] == "":
                    return json_response(True,"paramError","token不能为空！")

                zfClass = clients.get(request['token'], 0)
                if zfClass == 0:
                    return json_response(True,"tokenTimeOut","token过期！")

                #获取
                response = zfClass.get_table() 

                if response['error']:
                    return json_response(True,response['result'],response['message'])
                
                #分析
                try:
                    response['result'] = ctAnalytics(zfClass.setting).table_do(response['result'])
                except KeyError:
                    return json_response(True,"","页面分析出错！")

                #统一数据格式
                rowData = response['result']['ct_data']
                result    = {}
                result['title']=[
                    "课程",
                    "教师",
                    "地点",
                    "开始周",
                    "结束周",
                    "星期",
                    "节次",
                    "类型"
                ]
                result['data']=[]
                for one in rowData:
                    result['data'].append({
                        'kc'  : one['title'], #课程
                        'js'  : one['teacher'], #教师
                        'dd'  : one['address'], #地点
                        'ksz' : one['week_s'], #开始周
                        'jsz' : one['week_e'], #结束周
                        'xq'  : one['week_d'], #星期
                        'jc'  : one['class_n'], #节次
                        'lx'  : one['type'], #类型
                    })
                response['result']['campus_id']=zfClass.setting["id"]
                result['row'] = response['result']

                #返回
                return json_response(False,result,response['message'])

class exam:
        def POST(self):
                #获取并验证传入参数
                request = web.input()
                if not request.has_key('token') or request['token'] == "":
                    return json_response(True,"paramError","token不能为空！")

                zfClass = clients.get(request['token'], 0)
                if zfClass == 0:
                    return json_response(True,"tokenTimeOut","token过期！")

                #获取
                response = zfClass.get_exam() 

                if response['error']:
                    return json_response(True,response['result'],response['message'])
                
                #分析
                try:
                    response['result'] = ctAnalytics().exam_do(response['result'])
                except KeyError:
                    return json_response(True,"","页面分析出错！")

                #统一数据格式
                rowData = response['result']['data']
                result    = {}
                result['title']=[
                    "课程",
                    "姓名",
                    "时间",
                    "地点",
                    "形式",
                    "座位",
                    "校区"
                ]
                result['data']=[]
                for one in rowData:
                    result['data'].append({
                        'kc'  : one[0], #课程
                        'xm'  : one[1], #姓名
                        'sj'  : one[2], #时间
                        'di'  : one[3], #地点
                        'xs'  : one[4], #形式
                        'zw'  : one[5], #座位
                        'xq'  : one[6], #校区
                    })
                result['row'] = response['result']
                #返回
                return json_response(False,result,response['message'])

class score:
        def POST(self):
                #获取并验证传入参数
                request = web.input()
                if not request.has_key('token') or request['token'] == "":
                    return json_response(True,"paramError","token不能为空！")

                zfClass = clients.get(request['token'], 0)
                if zfClass == 0:
                    return json_response(True,"tokenTimeOut","token过期！")

                #获取
                response = zfClass.get_score() 

                if response['error']:
                    return json_response(True,response['result'],response['message'])
                
                #分析
                try:
                    response['result'] = ctAnalytics().score_do(response['result'])
                except KeyError:
                    return json_response(True,"","页面分析出错！")

                #统一数据格式
                rowData = response['result']['data']
                result    = {}
                result['title']=[
                    "课程",
                    "学分",
                    "学年",
                    "学期",
                    "学位课",
                    "成绩"
                ]
                result['data']=[]
                if zfClass.setting["name"] == "guoren":
                    for one in rowData:
                        result['data'].append({
                            'kc'  : one[3], #课程
                            'xf'  : one[6], #学分
                            'xn'  : one[0], #学年
                            'xq'  : one[1], #学期
                            'wxk' : '', #类型
                            'cj'  : one[8], #成绩
                        })
                else:
                    for one in rowData:
                        result['data'].append({
                            'kc'  : one[3], #课程
                            'xf'  : one[6], #学分
                            'xn'  : one[0], #学年
                            'xq'  : one[1], #学期
                            'wxk' : one[18], #类型
                            'cj'  : one[11], #成绩
                        })
                result['row'] = response['result']
                #返回
                return json_response(False,result,response['message'])